
package com.cnpinxi.controller.web.user;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.cnpinxi.controller.base.BaseController;
import com.cnpinxi.def.Constant;
import com.cnpinxi.domain.User;
import com.cnpinxi.domain.sms.SMSRegedit;
import com.cnpinxi.domain.weChat.WXJSConfig;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import com.cnpinxi.result.ResultObj;
import com.cnpinxi.service.UserService;
import com.cnpinxi.service.WeChatService;
import com.cnpinxi.tool.sms.SMSTools;
import com.cnpinxi.util.FixedData;
import com.cnpinxi.util.GenerateID;
import com.cnpinxi.util.MD5Tools;
import com.cnpinxi.util.WeiXinUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by lutao on 2017/7/14.
 */
@RequestMapping("/user")
@Controller
public class UserController extends BaseController {

    @Autowired
    UserService userService;
    @Autowired
    WeChatService weChatService;

    @RequestMapping(value = "/login")
    @ResponseBody
    public String login(HttpServletRequest request, User user) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            user.setPassWord(MD5Tools.MD5(user.getPassWord()));
            user = userService.login(user);
            HttpSession session = request.getSession();
            session.setAttribute(Constant.SESSION_KEY_USER_LOGIN, user);
            resultObj.setMsg("操作成功！");
            logger.info("dddddddddddddddddddddddddddddddddddd");
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    @RequestMapping(value = "/getWxjsConfig")
    @ResponseBody
    public String getWxjsConfig(HttpServletRequest request) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {

            String appId = FixedData.ENTERPRISE_APP_ID;

            String toUrl = "http://" + request.getServerName()
                    + request.getContextPath()      //项目名称
                    + request.getServletPath();     //请求页面或其他地址

            String queryStr = request.getQueryString();
            if (org.apache.commons.lang.StringUtils.isNotBlank(queryStr)) {
                toUrl += "?" + queryStr; //参数
            }
            logger.info("toURL============>>>>" + toUrl);
            toUrl = "http://www.cnpinxi.com/user/myQRCode.html";
            String ticket = weChatService.getTicket();
            WXJSConfig wxjsConfig = WeiXinUtils.getWXConfig(appId, toUrl, ticket);
            logger.info("wxjsConfig==>>" + wxjsConfig.toString());
            resultObj.setData(wxjsConfig);
        } catch (MyRunTimeExcption myRunTimeExcption) {
            myRunTimeExcption.printStackTrace();
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(myRunTimeExcption.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
        }
        return resultObj.toJson();
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logOut")
    @ResponseBody
    public String logOut(HttpServletRequest request) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            HttpSession session = request.getSession();
            session.invalidate();
            resultObj.setMsg("操作成功！");
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    @RequestMapping(value = "/getSMSCode")
    @ResponseBody
    public String sendSMSCode(HttpServletRequest request, String phone) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {

            String randomCode = GenerateID.getRandomNum(4, GenerateID.IS_ONLY_NUMBER);

            logger.info("randomCode=======>>>" + randomCode);
            SMSRegedit smsRegedit = new SMSRegedit();
            smsRegedit.setCode(randomCode);
            SendSmsResponse sendSmsResponse = SMSTools.sendSms(phone, SMSTools.SMS_TEMPLATE_CODE_REGISTE, smsRegedit);


            if (sendSmsResponse != null) {
                resultObj.setMsg(sendSmsResponse.getMessage());
            }
            HttpSession session = request.getSession();
            session.setAttribute(Constant.SESSION_KEY_RANDOM_CODE, randomCode);
        } catch (MyRunTimeExcption myRunTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(myRunTimeExcption.getMessage());
            myRunTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    @RequestMapping(value = "/regedit")
    @ResponseBody
    public String regedit(HttpServletRequest request, User user, String code) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            HttpSession session = request.getSession();

            checkCode(code, session);


            userService.regedit(user);
            session.setAttribute("user", user);
            resultObj.setMsg("操作成功！");
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    @RequestMapping(value = "/quickRegedit")
    @ResponseBody
    public String quickRegedit(HttpServletRequest request, User user) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {

            HttpSession session = request.getSession();
            String openId = (String) session.getAttribute(Constant.SESSION_OPEN_ID);
            //TODO 测试用OPENID，上线不能要
            //  openId="123465";
            user.setOpenId(openId);
            super.bindOpenId(session, user);
            resultObj.setMsg("操作成功！");
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    private Boolean checkCode(String code, HttpSession session) {
        String randomCode = (String) session.getAttribute(Constant.SESSION_KEY_RANDOM_CODE);
        if (StringUtils.isBlank(code)) {
            throw new MyRunTimeExcption("请输入短信验证码！");
        }
        if (!randomCode.equals(code)) {
            throw new MyRunTimeExcption("短信验证码错误！");
        }
        return true;
    }

    @RequestMapping(value = "/modifyUser")
    @ResponseBody
    public String modifyUser(User user, HttpServletRequest request, String code, String passWordOld) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            if (super.getUserBySession(request) != null) {
                user.setTid(super.getUserBySession(request).getTid());
            }

            if (user.getTid() == null) {
                user.setTid(userService.getUserByPhone(user.getPhone()).getTid());
            }

            if (StringUtils.isNotBlank(user.getPassWord())) {

                if (StringUtils.isNotBlank(passWordOld)) {
                    User user1 = userService.getUserById(user.getTid());
                    if (!MD5Tools.MD5(passWordOld).equals(user1.getPassWord())) {
                        throw new MyRunTimeExcption("原密码错误");
                    }
                    user.setPassWord(MD5Tools.MD5(user.getPassWord()));
                } else {
                    HttpSession session = request.getSession();
                    checkCode(code, session);
                    user.setPassWord(MD5Tools.MD5(user.getPassWord()));
                }

            }

            userService.modifyUser(user);

            modifySession(request);
            resultObj.setMsg("操作成功！");
        } catch (MyRunTimeExcption myRunTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(myRunTimeExcption.getMessage());
            myRunTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    /**
     * 跳转到产品名称页面
     *
     * @param request
     * @param response
     * @return
     */

    @RequestMapping("/myQRCode")
    public ModelAndView myQRCode(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView m = new ModelAndView();
        m.setViewName("/wap/user/myQRCode");
        HttpSession session = request.getSession();
        super.oauth2(request, response);
        String openId = (String) session.getAttribute(Constant.SESSION_OPEN_ID);
        try {
            User user = null;
            try {
                user = super.getUserByOpenId(openId);
            } catch (MyRunTimeExcption myRunTimeExcption) {
                myRunTimeExcption.printStackTrace();
            }
            if (user == null) {
                logger.info("user is null ,没有关联openID");
                user = (User) session.getAttribute(Constant.SESSION_KEY_USER_LOGIN);
                if (user != null) {
                    logger.info("user is not null ,已经登录");
                    if (StringUtils.isNotBlank(openId)) {
                        user.setOpenId(openId);
                        logger.info("modifyUser 绑定openId");
                        userService.modifyUser(user);
                    }

                }

            }
            if (user != null) {
                logger.info("user is not null ,updata session......................");
                session.setAttribute(Constant.SESSION_KEY_USER_LOGIN, user);
            }
            String sourceQRCode = user.getSourceQRCode();
            if (StringUtils.isBlank(sourceQRCode)) {
                userService.createSourceQRCode(user);
                modifySession(request);
            }
        } catch (Exception e) {
            logger.info("Exception==>>>>" + e.getMessage());
            e.printStackTrace();
        }


        return m;
    }


    @RequestMapping("/wap/login")
    public ModelAndView userLogin(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView m = new ModelAndView();
        m.setViewName("/wap/user/login");
        HttpSession session = request.getSession();
        super.oauth2(request, response);
        String openId = (String) session.getAttribute(Constant.SESSION_OPEN_ID);
        try {
            User user = null;
            try {
                user = super.getUserByOpenId(openId);
            } catch (MyRunTimeExcption myRunTimeExcption) {
                myRunTimeExcption.printStackTrace();
            }
            if (user == null) {
                logger.info("user is null ,没有关联openID");
                user = (User) session.getAttribute(Constant.SESSION_KEY_USER_LOGIN);
                if (user != null) {
                    logger.info("user is not null ,已经登录");
                    if (StringUtils.isNotBlank(openId)) {
                        user.setOpenId(openId);
                        logger.info("modifyUser 绑定openId");
                        userService.modifyUser(user);
                    }
                }
            }
            if (user != null) {
                logger.info("user is not null ,updata session......................");
                session.setAttribute(Constant.SESSION_KEY_USER_LOGIN, user);
            }

        } catch (Exception e) {
            logger.info("Exception==>>>>" + e.getMessage());
            e.printStackTrace();
        }
        return m;
    }
}
